package com.tingyuge.base.jdk.io.nio.buffer;

import com.tingyuge.base.jdk.io.nio.filechannel.FileChannelDemo1;
import org.junit.Test;

import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2022/1/9
 * @description
 */
public class BufferDemo1 {

    @Test
    public void buffer01() throws Exception {
        URL resource = FileChannelDemo1.class.getClass().getResource("/");
        String path = resource.getPath() + "buffer01.txt";
        path = path.replace("target/classes", "src/main/resources");
        System.out.println(path);
        RandomAccessFile accessFile = new RandomAccessFile(path, "rw");
        FileChannel fileChannel = accessFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //返回读取的字节数量
        int read = fileChannel.read(buffer);
        //-1 表示到了文件末尾
        while (read !=-1){
            //read 模式
            buffer.flip();

            while (buffer.hasRemaining()){
                System.out.print((char)buffer.get());
            }
            buffer.clear();
            read = fileChannel.read(buffer);
        }
        fileChannel.close();
    }

    @Test
    public void buffer02(){
        // 分配新的int缓冲区，参数为缓冲区容量
        IntBuffer intBuffer = IntBuffer.allocate(8);
        for (int i = 0; i < intBuffer.capacity(); i++) {
            int j = 2 * (i + 1);
            intBuffer.put(j);

        }
        // 重设此缓冲区，将限制设置为当前位置，然后将当前位置设置为 0
        intBuffer.flip();
        while (intBuffer.hasRemaining()){
            int value = intBuffer.get();
            System.out.println(value);
        }
    }

}
